#!/usr/bin/env python2.5

# import path

import nltk, re, format
import preterms
from preterms import *
from nltk import tree
from nltk.tree import *

def readout(leaves):
	"""Gives a readout of the leaves of a (sub)tree as if it were a sentence fragment."""
	out = ""
	for leaf in leaves:	out += leaf + " "
	return out.rstrip()

def init_messages(file):
	"""Prepares the list of messages for prompting the user when s/he has an ambiguity in the input, and the list of 
		templates for the sentences once the user chooses which format s/he prefers."""
	herald = open(file, 'r')
	message = dict()
	converts = dict()
	for news in herald:
		if ((news[0] != "#") and (news[0] != "\n")):
			# print news
			if (news.split("::")[0].strip() in message):
				message[news.split("::")[0].strip()].append(news.split("::")[1].strip())
			else:
				message[news.split("::")[0].strip()] = list([news.split("::")[1].strip()])
			if (news.split("::")[0].strip() in converts):
				converts[news.split("::")[0].strip()].append(news.split("::")[2].strip())
			else:
				converts[news.split("::")[0].strip()] = list([news.split("::")[2].strip()])
	# message["DT FW VP "] = 'Do you mean that "~~~0~~~ ~~~1~~~" or that "~~~0~~~ has ~~~1~~~"?'
	return (message, converts)

def init_sents(file):
	"""Prepares the list of sample sentences for testing the prompts."""
	herald = open(file, 'r')
	message = dict()
	for news in herald:
		if ((news[0] != "\n") and (news[0] != "#")):	message[news.split("::")[0].strip()] = news.split("::")[1].strip()
	return message

def toTuple(string):
	"""Converts a string in the form "#,#,#,#,...,#" into an ordered tuple."""
	vector = tuple()
	for num in string.split(","):
		vector += tuple([int(num)])
	return vector

def fitInto(tags, message):
	"""Fits the tagged terminals into the message template."""
	forms = "((\-|\||&|_|\+|\^|\$|@|=))"
	pattern = "~" + forms + "?#" + forms + "?~"
	madlib = message
	broken = tags.split()
	for x in range(len(broken)):
		label = re.sub("#", str(x), pattern)
		insert = broken[x]
		found = re.search(label, madlib)
		if found:	
			flag = str(found.group(1))[0]
			if (flag == "N"):	pass			## Corresponds to "None"
			if (flag == "_"):	insert = format.lower(insert)
			if (flag == "+"):	insert = format.upper(insert)
			if (flag == "-"):	insert = format.base(insert)
			if (flag == "="):	insert = format.base2(insert)
			if (flag == "@"):	insert = format.poss(format.lower(insert))
			if (flag == "^"):	insert = format.bool(insert, broken[x - 2])
			if (flag == "$"):	insert = format.poss(insert)
			if (flag == "|"):	insert = format.passive(insert)
			if (flag == "&"):	insert = format.gerund(insert)
			madlib = re.sub(label, insert, madlib)
	return madlib

def reformat(sentence, template):
	"""Reformats a sentence, converting it to fit in the given format."""
	words = sentence.split()
	new = ""
	for spot in template.split():
		 new += words[sport] + " "
	return new[:-1]

## Test code:
if (__name__ == "__main__"):
	(messages, formats) = init_messages(sys.argv[1])
	sents = init_sents(sys.argv[2])
	for temp in messages.keys():
		for late in messages[temp]:
			print fitInto(sents[temp], late)
		for never in formats[temp]:
			print fitInto(sents[temp], never)
			# print reformat(sents[temp], never)
	
	## Print messages:
	# for message in messages:
	#	print message, " ", messages[message]
